#Region " Imports "

Imports System
Imports System.Data
Imports System.Data.SqlClient
Imports System.Drawing
Imports System.IO
Imports System.Web.UI.ScriptManager
Imports System.Web
Imports System.Web.Security
Imports System.Web.UI
Imports System.Web.UI.WebControls.WebParts
Imports System.Web.UI.HtmlControls
Imports Microsoft.VisualBasic

Imports ICSharpCode.SharpZipLib.BZip2
Imports ICSharpCode.SharpZipLib.Zip
Imports ICSharpCode.SharpZipLib.Zip.Compression
Imports ICSharpCode.SharpZipLib.Zip.Compression.Streams
Imports ICSharpCode.SharpZipLib.GZip

Imports BlazeApps.Library.NVLs
Imports BlazeApps.Library.Resources
Imports BlazeApps.Library.Themes
Imports BlazeApps.Library.Forum
Imports BlazeApps.Library.TreeViews
Imports BlazeApps.Library.Form

Imports BA.Attachments
Imports BA.Images
Imports BA.Validators

Imports FredCK.FCKeditorV2

#End Region

Public Class WebControlBase
    Inherits WebBase

#Region " Declarations "

    Protected Resource As ResourceDetail

#End Region

#Region " Regular Expressions "

    Protected EmailReGEx As String = "^.+@[^\.].*\.[a-z]{2,}$"
    Protected NoSpacesReGEx As String = "^[a-zA-Z0-9]+$"
    Protected NoSpacesLettersReGEx As String = "^[a-zA-Z]+$"
    Protected NoSpacesNumbersReGEx As String = "^[0-9]+$"
    Protected UppercaseReGEx As String = "^\s*[A-Z,.!?\s]+\s*$"
    Protected LowercaseReGEx As String = "^\s*[a-z,.!?\s]+\s*$"
    Protected NumbersOnlyReGEx As String = "[0-9]"
    Protected LettersOnlyReGEx As String = "^\s*[a-zA-Z\s]+\s*$"
    Protected WebAddressRegEx As String = "\s(((h|H?)(t|T?)(t|T?)(p|P?)(s|S?))*://)?(www.|[a-zA-Z0-9].)[a-zA-Z0-9\-\.]+\.[a-zA-Z]?/?([a-zA-Z0-9\-\._\?\,\'/\\\+&%\$#\=~])*[^\.\,\)\(\s]*"

#End Region

#Region " Enums "

    Protected Enum ItemTypeList
        Article = 1
        Suggestion = 2
        Page = 3
    End Enum

    Protected Enum StatusList
        NewItem = 1
        Approved = 2
        Denied = 3
        Edit = 4
        Disabled = 5
        Enabled = 6
    End Enum

    Protected Enum AccessTypeList
        PrivateItem = 1
        PublicItem = 2
    End Enum

    Protected Enum EditorPageType
        SingleEditor = 0
        DynamicRepeaterEditors = 1
        CommentEditor = 2
		ForumEditor = 3
		NewsEditor = 4
    End Enum

    Protected Enum FormControlType
        SingleTextBox = 1
        MultilineTextBox = 2
        SelectionList = 3
        DateTimeBox = 4
        MultipleChoiceSingleAnswer = 5
        MultipleChoiceMultipleAnswer = 6
        MatrixOneAnswerPerRow = 7
        MatrixMultipleAnswersPerRow = 8
    End Enum

    ''' <summary>
    ''' This is used in conjunction with the ValidationDataTypes that are used for the compare validator
    ''' </summary>
    ''' <remarks></remarks>
    Protected Enum SecondaryValidatorTypes
        Email = 6
        NoSpaces = 7
        NoSpacesLetters = 8
        NoSpacesNumbers = 9
        Uppercase = 10
        Lowercase = 11
        NumbersOnly = 12
        LettersOnly = 13
        WebAddress = 14
    End Enum

#End Region

#Region " Page "

    Private Sub Page_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.PreRender
        CreatePagingLinks()
    End Sub

#End Region

#Region " Trees "

    Public Sub PopulateRootLevel(ByVal TreeControl As TreeView, ByVal Type As TreeViewNodes.TreeType, ByVal UserID As Guid)
        Dim TreeParent As New TreeViewNodes

        PopulateNodes(TreeParent.GetTreeParent(Type, UserID), TreeControl.Nodes)

    End Sub

    Public Sub PopulateSubLevel(ByVal ParentNodeID As String, ByVal ParentNode As TreeNode, ByVal Type As TreeViewNodes.TreeType, ByVal UserID As Guid)
        Dim TreeChild As New TreeViewNodes

        PopulateNodes(TreeChild.GetTreeChild(ParentNodeID, Type, UserID), ParentNode.ChildNodes)

    End Sub

    Public Sub PopulateNodes(ByVal DS As DataSet, ByVal Nodes As TreeNodeCollection)
        Dim iI As Integer

        For iI = 0 To DS.Tables(0).Rows.Count - 1
            Dim TN As New TreeNode
            TN.Text = DS.Tables(0).Rows(iI).Item(Trim("name")).ToString
            TN.Value = DS.Tables(0).Rows(iI).Item(Trim("nodeid")).ToString

            Nodes.Add(TN)

            TN.PopulateOnDemand = (CType(DS.Tables(0).Rows(iI).Item(Trim("childnodecount")).ToString, Integer) > 0)
        Next

	End Sub

#End Region

#Region " Drop Down Lists "

#Region " Load List Methods "

    Protected Sub LoadPageSize(ByVal Control As DropDownList)

        With Control
            .Items.Clear()
            .Items.Add(New ListItem("5", "5"))
            .Items.Add(New ListItem("10", "10"))
            .Items.Add(New ListItem("15", "15"))
            .Items.Add(New ListItem("20", "20"))
            .Items.Add(New ListItem("25", "25"))
            .Items.Add(New ListItem("50", "50"))
            .Items.Add(New ListItem("100", "100"))
            .Items.Add(New ListItem("200", "200"))
            .Items.Add(New ListItem("300", "300"))
            .Items.Add(New ListItem("400", "400"))
            .Items.Add(New ListItem("500", "500"))
            .SelectedValue = ItemsPerPage
        End With

    End Sub

    Protected Sub LoadFileType(ByVal Control As DropDownList)

        With Control
            .Items.Clear()
            .Items.Add(New ListItem("Image", "0"))
            .Items.Add(New ListItem("Video", "1"))
            .Items.Add(New ListItem(DropDownDefaultText, DropDownDefaultValue))
            .SelectedValue = DropDownDefaultValue
        End With

    End Sub

    Protected Sub LoadStatusList(ByVal Control As DropDownList)
        Dim StatusList As New Status

        With Control
            .DataSource = StatusList.GetStatusList()
            .DataValueField = "int_value"
            .DataTextField = "longdesc"
            .DataBind()
            .Items.Add(New ListItem(DropDownDefaultText, DropDownDefaultValue))
            .SelectedValue = DropDownDefaultValue
        End With
    End Sub

    Protected Sub LoadDifficultyLevelList(ByVal Control As DropDownList)
        Dim LevelList As New DifficultyLevel

        With Control
            .DataSource = LevelList.GetDifficultyList()
            .DataValueField = "int_value"
            .DataTextField = "longdesc"
            .DataBind()
            .Items.Add(New ListItem(DropDownDefaultText, DropDownDefaultValue))
            .SelectedValue = DropDownDefaultValue
        End With
    End Sub

    Protected Sub LoadAccessTypeList(ByVal Control As DropDownList)
        Dim AccessList As New AccessType

        With Control
            .DataSource = AccessList.GetAccessTypeList()
            .DataValueField = "int_value"
            .DataTextField = "longdesc"
            .DataBind()
            .Items.Add(New ListItem(DropDownDefaultText, DropDownDefaultValue))
            .SelectedValue = DropDownDefaultValue
        End With
    End Sub

    Protected Sub LoadTemplateList(ByVal Control As DropDownList)
        Dim TemplateList As New Template

        With Control
            .DataSource = TemplateList.GetTemplateList()
            .DataValueField = "templateid"
            .DataTextField = "templatename"
            .DataBind()
            .Items.Add(New ListItem(DropDownDefaultText, DropDownDefaultValue))
            '.SelectedValue = "00000000-0000-0000-0000-000000000000"
            .SelectedValue = DropDownDefaultValue
        End With
    End Sub

    Protected Sub LoadItemTypeList(ByVal Control As DropDownList)
        Dim TypeList As New ItemType

        With Control
            .DataSource = TypeList.GetItemTypeList()
            .DataValueField = "int_value"
            .DataTextField = "longdesc"
            .DataBind()
            .Items.Add(New ListItem(DropDownDefaultText, DropDownDefaultValue))
            .SelectedValue = DropDownDefaultValue
        End With
    End Sub

    Protected Sub LoadThemeList(ByVal Control As DropDownList)
        Dim Theme As New ThemeList

        With Control
            .DataSource = Theme.GetThemeList()
            .DataValueField = "themefolder"
            .DataTextField = "themename"
            .DataBind()
            .Items.Add(New ListItem(ConfigTheme, ConfigTheme))
            .SelectedValue = ConfigTheme
        End With
    End Sub

    Protected Sub LoadBoardList(ByVal Control As DropDownList)
        Dim Board As New BoardList

        With Control
            .DataSource = Board.GetBoardSelectionList()
            .DataValueField = "BoardID"
            .DataTextField = "BoardName"
            .DataBind()
            .Items.Add(New ListItem(DropDownDefaultText, DropDownDefaultGuidValue))
            .SelectedValue = DropDownDefaultGuidValue
        End With
    End Sub

    Protected Sub LoadCategoryList(ByVal Control As DropDownList)
        Dim Category As New CategoryList

        With Control
            .DataSource = Category.GetCategorySelectionList()
            .DataValueField = "CategoryID"
            .DataTextField = "CategoryName"
            .DataBind()
            .Items.Add(New ListItem(DropDownDefaultText, DropDownDefaultGuidValue))
            .SelectedValue = DropDownDefaultGuidValue
        End With
    End Sub

    Protected Sub LoadHourList(ByVal Control As DropDownList)
        With Control
            .Items.Add(New ListItem("1", "1"))
            .Items.Add(New ListItem("2", "2"))
            .Items.Add(New ListItem("3", "3"))
            .Items.Add(New ListItem("4", "4"))
            .Items.Add(New ListItem("5", "5"))
            .Items.Add(New ListItem("6", "6"))
            .Items.Add(New ListItem("7", "7"))
            .Items.Add(New ListItem("8", "8"))
            .Items.Add(New ListItem("9", "9"))
            .Items.Add(New ListItem("10", "10"))
            .Items.Add(New ListItem("11", "11"))
            .Items.Add(New ListItem("12", "12"))
            .Items.Add(New ListItem(DropDownDefaultText, DropDownDefaultValue))
            .SelectedValue = DropDownDefaultValue
        End With
    End Sub

    Protected Sub LoadMinuteList(ByVal Control As DropDownList)
        With Control
            .Items.Add(New ListItem("00", "0"))
            .Items.Add(New ListItem("15", "15"))
            .Items.Add(New ListItem("30", "30"))
            .Items.Add(New ListItem("45", "45"))
            .Items.Add(New ListItem(DropDownDefaultText, DropDownDefaultValue))
            .SelectedValue = DropDownDefaultValue
        End With
    End Sub

    Protected Sub LoadMeridianList(ByVal Control As DropDownList)
        With Control
            .Items.Add(New ListItem("AM", "AM"))
            .Items.Add(New ListItem("PM", "PM"))
            .Items.Add(New ListItem(DropDownDefaultText, DropDownDefaultValue))
            .SelectedValue = DropDownDefaultValue
        End With
    End Sub

    Protected Sub LoadLongDayList(ByVal Control As DropDownList)
        With Control
            .Items.Add(New ListItem(Resources.Resource.Sunday.Trim, Resources.Resource.Sunday.Trim))
            .Items.Add(New ListItem(Resources.Resource.Monday.Trim, Resources.Resource.Monday.Trim))
            .Items.Add(New ListItem(Resources.Resource.Tuesday.Trim, Resources.Resource.Tuesday.Trim))
            .Items.Add(New ListItem(Resources.Resource.Wednesday.Trim, Resources.Resource.Wednesday.Trim))
            .Items.Add(New ListItem(Resources.Resource.Thursday.Trim, Resources.Resource.Thursday.Trim))
            .Items.Add(New ListItem(Resources.Resource.Friday.Trim, Resources.Resource.Friday.Trim))
            .Items.Add(New ListItem(Resources.Resource.Saturday.Trim, Resources.Resource.Saturday.Trim))
            .Items.Add(New ListItem(DropDownDefaultText, DropDownDefaultValue))
            .SelectedValue = DropDownDefaultValue
        End With
    End Sub

    Protected Sub LoadLongMonthList(ByVal Control As DropDownList)
        With Control
            .Items.Add(New ListItem(Resources.Resource.January.Trim))
            .Items.Add(New ListItem(Resources.Resource.February.Trim))
            .Items.Add(New ListItem(Resources.Resource.March.Trim))
            .Items.Add(New ListItem(Resources.Resource.April.Trim))
            .Items.Add(New ListItem(Resources.Resource.May.Trim))
            .Items.Add(New ListItem(Resources.Resource.June.Trim))
            .Items.Add(New ListItem(Resources.Resource.July.Trim))
            .Items.Add(New ListItem(Resources.Resource.August.Trim))
            .Items.Add(New ListItem(Resources.Resource.September.Trim))
            .Items.Add(New ListItem(Resources.Resource.October.Trim))
            .Items.Add(New ListItem(Resources.Resource.November.Trim))
            .Items.Add(New ListItem(Resources.Resource.December.Trim))
            .SelectedValue = DateTime.Today.ToString("MMMM")
        End With
    End Sub

    Protected Sub LoadDayList(ByVal Control As DropDownList, ByVal SelectedMonth As Integer)

        With Control
            For day As Integer = 1 To DateTime.DaysInMonth(DateTime.Now.Year, SelectedMonth)
                .Items.Add(New ListItem(day.ToString(), day.ToString()))
            Next
            .SelectedValue = DateTime.Now.Day
        End With

    End Sub

    Protected Sub LoadDayList(ByVal Control As DropDownList)

        With Control
            For day As Integer = 1 To DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month)
                .Items.Add(New ListItem(day.ToString(), day.ToString()))
            Next
            .SelectedValue = DateTime.Now.Day
        End With

	End Sub

	Protected Sub LoadRolesList(ByVal RoleList As CheckBoxList)

		With RoleList
			.DataSource = Roles.GetAllRoles
			.DataBind()
			.DataTextField = "Item"
			.DataValueField = "Item"
		End With

	End Sub

    Protected Sub LoadControlPickerList(ByVal Control As DropDownList)
        Dim FormList As New FormList

        With Control
            .DataSource = FormList.GetControlList()
            .DataValueField = "formcontrolid"
            .DataTextField = "controlname"
            .DataBind()
            .Items.Add(New ListItem(DropDownDefaultText, DropDownDefaultGuidValue))
            .SelectedValue = "00000000-0000-0000-0000-000000000000"
        End With
    End Sub

    Protected Sub LoadFormTypeList(ByVal Control As DropDownList)
        Dim FormTypeList As New FormType

        With Control
            .DataSource = FormTypeList.GetFormTypeList()
            .DataValueField = "int_value"
            .DataTextField = "longdesc"
            .DataBind()
            .Items.Add(New ListItem(DropDownDefaultText, DropDownDefaultValue))
            .SelectedValue = DropDownDefaultValue
        End With
    End Sub

    Protected Sub LoadRows(ByVal Control As DropDownList)

        With Control
            .Items.Clear()
            .Items.Add(New ListItem("1", "1"))
            .Items.Add(New ListItem("2", "2"))
            .Items.Add(New ListItem("3", "3"))
            .Items.Add(New ListItem("4", "4"))
            .Items.Add(New ListItem("5", "5"))
            .Items.Add(New ListItem("6", "6"))
            .Items.Add(New ListItem("7", "7"))
            .Items.Add(New ListItem("8", "8"))
            .Items.Add(New ListItem("9", "9"))
            .Items.Add(New ListItem("10", "10"))
            .Items.Add(New ListItem("20", "20"))
            .SelectedValue = "4"
        End With

    End Sub

    Protected Sub LoadCols(ByVal Control As DropDownList)

        With Control
            .Items.Clear()
            .Items.Add(New ListItem("20", "20"))
            .Items.Add(New ListItem("30", "30"))
            .Items.Add(New ListItem("40", "40"))
            .Items.Add(New ListItem("50", "50"))
            .Items.Add(New ListItem("60", "60"))
            .Items.Add(New ListItem("70", "70"))
            .Items.Add(New ListItem("80", "80"))
            .SelectedValue = "50"
        End With

    End Sub

    Protected Sub LoadRegularExpressions(ByVal Control As DropDownList)

        With Control
            .Items.Clear()
            .Items.Add(New ListItem("Email", "6"))
            .Items.Add(New ListItem("No Spaces", "7"))
            .Items.Add(New ListItem("No Spaces (Letters)", "8"))
            .Items.Add(New ListItem("No Spaces (Numbers)", "9"))
            .Items.Add(New ListItem("Uppercase", "10"))
            .Items.Add(New ListItem("Lowercase", "11"))
            .Items.Add(New ListItem("Numbers Only", "12"))
            .Items.Add(New ListItem("Letters Only", "13"))
            .Items.Add(New ListItem("Web Address", "14"))
            .SelectedValue = "6"
        End With

    End Sub

    Protected Sub LoadComparValidatorTypes(ByVal Control As DropDownList)

        With Control
            .Items.Clear()
            .Items.Add(New ListItem("Integer", "1"))
            .Items.Add(New ListItem("Double", "2"))
            .Items.Add(New ListItem("Date", "3"))
            .Items.Add(New ListItem("Currency", "4"))
            .Items.Add(New ListItem("String", "5")) 'This is the end of the built in validation types
            .Items.Add(New ListItem("Email", "6")) 'This point forward will use regular expressions
            .Items.Add(New ListItem("No Spaces", "7"))
            .Items.Add(New ListItem("No Spaces (Letters)", "8"))
            .Items.Add(New ListItem("No Spaces (Numbers)", "9"))
            .Items.Add(New ListItem("Uppercase", "10"))
            .Items.Add(New ListItem("Lowercase", "11"))
            .Items.Add(New ListItem("Numbers Only", "12"))
            .Items.Add(New ListItem("Letters Only", "13"))
            .Items.Add(New ListItem("Web Address", "14"))
            .SelectedValue = "5"
        End With

    End Sub

    Protected Sub LoadChoiceLayout(ByVal Control As DropDownList)

        With Control
            .Items.Clear()
            .Items.Add(New ListItem("Horizontal", "0"))
            .Items.Add(New ListItem("Vertical", "1"))
            .SelectedValue = "0"
        End With

    End Sub

    Protected Sub LoadForumList(ByVal Control As DropDownList, ByVal SelectedValue As String)
        Dim Forum As New ForumList

        With Control
            .DataSource = Forum.GetForumSelectionList()
            .DataValueField = "forumid"
            .DataTextField = "forumname"
            .DataBind()
            .SelectedValue = SelectedValue
        End With
    End Sub

#End Region

#Region " Get Selected Item Methods "

    Protected Function GetGuidFromSelectedItem(ByVal Control As DropDownList) As Guid
        Return New Guid(Control.SelectedValue)
    End Function

    Protected Function GetStringFromSelectedItem(ByVal Control As DropDownList) As String
        Return New String(Control.SelectedValue)
    End Function

    Protected Function GetIntegerFromSelectedItem(ByVal Control As DropDownList) As Integer
        Return CType(Control.SelectedValue, Integer)
    End Function


#End Region

#Region " Events "

    Protected Sub uxPageSizeDropDownList_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs)
        Me.PageNumber = 0
        BindDataItems()
    End Sub

#End Region

#End Region

#Region " Image Buttons "

#Region " Events "

    Protected Sub uxRefreshImageButton_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs)
        Me.PageNumber = 0
        BindDataItems()
    End Sub

#End Region

#End Region

#Region " Resource Gallery Methods "

    Protected Function InsertResource(ByVal FileUploadSource As FileUpload, ByVal ThumbUploadSource As FileUpload, ByVal ResourceTitle As String, ByVal ResourceDescription As String, ByVal ResourceFolder As Guid, ByVal Type As UploadType, ByVal PrivateItem As Boolean) As Guid

        Return SaveResource(FileUploadSource, ThumbUploadSource, ResourceTitle, ResourceDescription, Guid.Empty, ResourceFolder, UploadType.NewItem, PrivateItem)

    End Function

    Protected Function UpdateResource(ByVal FileUploadSource As FileUpload, ByVal ThumbUploadSource As FileUpload, ByVal ResourceTitle As String, ByVal ResourceDescription As String, ByVal ResourceID As Guid, ByVal Type As UploadType, ByVal PrivateItem As Boolean) As Guid

        Return SaveResource(FileUploadSource, ThumbUploadSource, ResourceTitle, ResourceDescription, ResourceID, Guid.Empty, UploadType.UpdateItem, PrivateItem)

    End Function

    Private Function SaveResource(ByVal FileUploadSource As FileUpload, ByVal ThumbUploadSource As FileUpload, ByVal ResourceTitle As String, ByVal ResourceDescription As String, ByVal ResourceID As Guid, ByVal ResourceFolder As Guid, ByVal Type As UploadType, ByVal PrivateItem As Boolean) As Guid

        If Type = UploadType.NewItem Then
            Resource = ResourceDetail.NewResourceDetail
        End If

        If Type = UploadType.UpdateItem Then
            Resource = ResourceDetail.GetResourceDetail(ResourceID)
        End If

        Dim Attachment As New AttachmentUtility
        Dim ImageFile As New ImageUtility
        Dim Thumb As Byte()

        Attachment.FileField = FileUploadSource
        ImageFile.FileField = FileUploadSource

        If InStr(FileUploadSource.PostedFile.ContentType, "image/") Then
            Attachment.Image = ImageFile.GetImageFromPostedFile(FileUploadSource)
            Thumb = ImageFile.CreateThumbnail(Attachment.GetStreamFromImage, ThumbWidth, ThumbHeight)
            Resource.resource = Attachment.GetByteArrayFromImage
        ElseIf (InStr(FileUploadSource.PostedFile.ContentType, "video/") Or Path.GetExtension(FileUploadSource.PostedFile.FileName.ToString).ToUpper() = ".FLV") Or Path.GetExtension(FileUploadSource.PostedFile.FileName.ToString).ToUpper() = ".SWF" Then

            If ThumbUploadSource.HasFile Then
                Dim ThumbImageFile As New ImageUtility
                ThumbImageFile.FileField = ThumbUploadSource

                Attachment.Image = ThumbImageFile.GetImageFromPostedFile(ThumbUploadSource)
            Else
                If FileUploadSource.PostedFile.ContentType.IndexOf("video/") = 0 Then
                    Attachment.Image = ImageFile.GetEmbeddedImage(FileUploadSource.PostedFile.FileName, ImageUtility.FileContentType.video)
                End If

                If FileUploadSource.PostedFile.FileName.IndexOf(".flv") > 0 Then
                    Attachment.Image = ImageFile.GetEmbeddedImage(FileUploadSource.PostedFile.FileName, ImageUtility.FileContentType.flash)
                End If

                If FileUploadSource.PostedFile.FileName.IndexOf(".swf") > 0 Then
                    Attachment.Image = ImageFile.GetEmbeddedImage(FileUploadSource.PostedFile.FileName, ImageUtility.FileContentType.flash)
                End If
            End If

            Thumb = ImageFile.CreateThumbnail(Attachment.GetStreamFromImage, ThumbWidth, ThumbHeight)
            Resource.resource = Attachment.GetByteArrayFromFileField

        Else
            Attachment.Image = ImageFile.GetEmbeddedImage(FileUploadSource.PostedFile.FileName, ImageUtility.FileContentType.file)
            Thumb = ImageFile.CreateThumbnail(Attachment.GetStreamFromImage, ThumbWidth, ThumbHeight)
            Resource.resource = Attachment.GetByteArrayFromFileField
        End If

        Resource.resourcetitle = ResourceTitle.Trim
        Resource.resourcedesc = ResourceDescription.Trim
        Resource.resourcename = Attachment.FileFieldFilename.Trim
        Resource.resourcesize = FileUploadSource.PostedFile.ContentLength
        Resource.contenttype = FileUploadSource.PostedFile.ContentType
        Resource.thumbnail = Thumb
        Resource.Userid = CurrentUserID
        Resource.Private = PrivateItem

        If ResourceFolder <> Guid.Empty Then
            Resource.resourcefolderid = ResourceFolder
        End If

        Resource.Save()

        Return Resource.resourceid

    End Function

    Protected Sub GetResource(ByVal ResourceID As Guid)
        Dim Resource As ResourceDetail = ResourceDetail.GetResourceDetail(ResourceID)

        With Response
            .Clear()
            .ContentType = Resource.contenttype
            .AddHeader("Content-Disposition", "filename=" & Resource.resourcename)
            .BinaryWrite(Resource.resource)
            .End()
        End With

    End Sub

    Protected Sub GetThumbnail(ByVal ResourceID As Guid)

        Dim Resource As ResourceDetail = ResourceDetail.GetResourceDetail(ResourceID)

        With Response
            .Clear()
            .ContentType = Resource.contenttype
            .AddHeader("Content-Disposition", "filename=" & Resource.resourcename)
            .BinaryWrite(Resource.thumbnail)
            .End()
        End With

    End Sub

#End Region

#Region " FCK Editor "

#Region " Members "

	Private _FCKEditor As FCKeditor
	Private _FCKRepeater As Repeater

#End Region

#Region " Properties "

	Protected Property FCKEditor() As FCKeditor
		Get
			Return _FCKEditor
		End Get
		Set(ByVal value As FCKeditor)
			_FCKEditor = value
		End Set
	End Property

	Protected Property FCKRepeater() As Repeater
		Get
			Return _FCKRepeater
		End Get
		Set(ByVal value As Repeater)
			_FCKRepeater = value
		End Set
	End Property

#End Region

#Region " Methods "

	Protected Function BuildFCKEditor(ByVal EditorLocation As EditorPageType) As Boolean

		If EditorLocation = EditorPageType.CommentEditor OrElse EditorLocation = EditorPageType.ForumEditor Then
			_FCKEditor.BasePath = "~/fckeditor/"
			_FCKEditor.ToolbarSet = "BASimpleSet"
		End If

		If EditorLocation = EditorPageType.SingleEditor Then
			_FCKEditor.BasePath = "~/fckeditor/"
			_FCKEditor.ToolbarSet = "BASimpleSet"
		End If

		If EditorLocation = EditorPageType.NewsEditor Then
			_FCKEditor.BasePath = "~/fckeditor/"
			_FCKEditor.ToolbarSet = "BAEditorSet"
		End If

		If EditorLocation = EditorPageType.DynamicRepeaterEditors Then
			Dim iI As Integer

			For iI = 0 To _FCKRepeater.Items.Count - 1
				Dim ctl As Control = _FCKRepeater.Items(iI).FindControl("uxTemplate")
				Dim lit As Literal = ctl.Controls.Item(0).FindControl("uxTitleLiteral")
				Dim TextBox As FCKeditor = ctl.Controls.Item(0).FindControl("uxEditorTextbox")

				TextBox.BasePath = "~/fckeditor/"
				TextBox.ToolbarSet = "BAEditorSet"
			Next

		End If

		Return True

	End Function

#End Region

#End Region

#Region " Zip Files "

    Public Sub ExtractZipFile(ByVal FileUploadSource As FileUpload, ByRef path As String)

        If Not (Directory.Exists(String.Format("{0}\Upload", PhysicalAppPath))) Then
            Directory.CreateDirectory(String.Format("{0}\Upload", PhysicalAppPath))
        End If

        Dim TempFile As String = String.Format("{0}\Upload\{1}", PhysicalAppPath, String.Format("{0}_{1}", Guid.NewGuid, FileUploadSource.FileName))

        FileUploadSource.SaveAs(TempFile)

        Dim s As ZipInputStream = New ZipInputStream(File.OpenRead(TempFile))

        Dim theEntry As ZipEntry
        theEntry = s.GetNextEntry()

        While Not theEntry Is Nothing

            Dim directoryName As String = System.IO.Path.GetDirectoryName(theEntry.Name)
            Dim fileName As String = System.IO.Path.GetFileName(theEntry.Name)

            Directory.CreateDirectory(path & " \" & directoryName)

            If (fileName <> String.Empty) Then

                Dim streamWriter As FileStream = File.Create(path & " \" & theEntry.Name)

                Dim size As Integer = 2048
                Dim data(2048) As Byte

                While (True)
                    size = s.Read(data, 0, data.Length)
                    If size > 0 Then
                        streamWriter.Write(data, 0, size)
                    Else
                        Exit While
                    End If
                End While

                streamWriter.Close()

            End If

            theEntry = s.GetNextEntry()

        End While

        s.Close()

        File.Delete(TempFile)

    End Sub

#End Region

#Region " Paging Controls "

#Region " Members "

    Private _RepeaterTop As Repeater
    Private _RepeaterBottom As Repeater

    Private _PagingTopPanel As Panel
    Private _PagingBottomPanel As Panel

    Private _NextTopLinkButton As LinkButton
    Private _PreviousTopLinkButton As LinkButton
    Private _NextBottomLinkButton As LinkButton
    Private _PreviousBottomLinkButton As LinkButton

    Private _DataPage As New PagedDataSource
    Private _PageSize As Integer = 10
    Private _PagesToDisplay As Integer = 10
    Private _RecordCount As Integer = -1
    Private _PageNumber As Integer = 0

    Private _PageMessageDisplayLabel As Label
    Private _ItemsPerPageLabel As Label
    Private _ItemsPerPageDropDown As DropDownList
    Private _PagerInfoLabel As Label

#End Region

#Region " Properties "

    Protected Property PageNumber() As Integer
        Get
            If Not (ViewState("PageNumber") Is Nothing) Then
                Return Convert.ToInt32(ViewState("PageNumber"))
            Else
                Return _PageNumber
            End If
        End Get
        Set(ByVal value As Integer)
            ViewState("PageNumber") = value
        End Set
    End Property

    Protected Property PageCount() As Integer
        Get
            If Not (ViewState("PageCount") Is Nothing) Then
                Return Convert.ToInt32(ViewState("PageCount"))
            Else
                Return 0
            End If
        End Get
        Set(ByVal value As Integer)
            ViewState("PageCount") = value
        End Set
    End Property

    Protected Property RepeaterTop() As Repeater
        Get
            Return _RepeaterTop
        End Get
        Set(ByVal value As Repeater)
            _RepeaterTop = value
        End Set
    End Property

    Protected Property RepeaterBottom() As Repeater
        Get
            Return _RepeaterBottom
        End Get
        Set(ByVal value As Repeater)
            _RepeaterBottom = value
        End Set
    End Property

    Protected Property PagingTopPanel() As Panel
        Get
            Return _PagingTopPanel
        End Get
        Set(ByVal value As Panel)
            _PagingTopPanel = value
        End Set
    End Property

    Protected Property PagingBottomPanel() As Panel
        Get
            Return _PagingBottomPanel
        End Get
        Set(ByVal value As Panel)
            _PagingBottomPanel = value
        End Set
    End Property

    Protected Property NextTopLinkButton() As LinkButton
        Get
            Return _NextTopLinkButton
        End Get
        Set(ByVal value As LinkButton)
            _NextTopLinkButton = value
        End Set
    End Property

    Protected Property PreviousTopLinkButton() As LinkButton
        Get
            Return _PreviousTopLinkButton
        End Get
        Set(ByVal value As LinkButton)
            _PreviousTopLinkButton = value
        End Set
    End Property

    Protected Property NextBottomLinkButton() As LinkButton
        Get
            Return _NextBottomLinkButton
        End Get
        Set(ByVal value As LinkButton)
            _NextBottomLinkButton = value
        End Set
    End Property

    Protected Property PreviousBottomLinkButton() As LinkButton
        Get
            Return _PreviousBottomLinkButton
        End Get
        Set(ByVal value As LinkButton)
            _PreviousBottomLinkButton = value
        End Set
    End Property

    Protected Property DataPage() As PagedDataSource
        Get
            Return _DataPage
        End Get
        Set(ByVal value As PagedDataSource)
            _DataPage = value
        End Set
    End Property

    Protected Property PageSize() As Integer
        Get
            Return _PageSize
        End Get
        Set(ByVal value As Integer)
            _PageSize = value
        End Set
    End Property

    Protected Property PagesToDisplay() As Integer
        Get
            Return _PagesToDisplay
        End Get
        Set(ByVal value As Integer)
            _PagesToDisplay = value
        End Set
    End Property

    Protected Property RecordCount() As Integer
        Get
            Return _RecordCount
        End Get
        Set(ByVal value As Integer)
            _RecordCount = value
        End Set
    End Property

    Public Property PageMessageDisplayLabel() As Label
        Get
            Return _PageMessageDisplayLabel
        End Get
        Set(ByVal value As Label)
            _PageMessageDisplayLabel = value
        End Set
    End Property

    Public Property ItemsPerPageLabel() As Label
        Get
            Return _ItemsPerPageLabel
        End Get
        Set(ByVal value As Label)
            _ItemsPerPageLabel = value
        End Set
    End Property

    Public Property ItemsPerPageDropDown() As DropDownList
        Get
            Return _ItemsPerPageDropDown
        End Get
        Set(ByVal value As DropDownList)
            _ItemsPerPageDropDown = value
        End Set
    End Property

    Public Property PagerInfoLabel() As Label
        Get
            Return _PagerInfoLabel
        End Get
        Set(ByVal value As Label)
            _PagerInfoLabel = value
        End Set
    End Property

#End Region

#Region " Methods "

    Public Overridable Overloads Sub BindDataItems()

    End Sub

    Protected Overridable Overloads Sub BindDataItems(ByVal PageNum As Integer)

    End Sub

    Protected Overridable Overloads Sub BindDataItems(ByVal NodeID As String)

    End Sub

#End Region

#Region " Navigation Methods "

    Protected Sub CreatePagingLinks()

        Try

            If Not _DataPage.PageCount = 0 Then

                PageCount = _DataPage.PageCount
                Dim LowerLimit As Integer
                Dim UpperLimit As Integer
                Dim PagerDisplay As New StringBuilder
                Dim PageStartRange As Integer
                Dim PageEndRange As Integer

                PageStartRange = Me._DataPage.CurrentPageIndex * Me._PageSize + 1
                PageEndRange = Math.Min((PageStartRange + Me._PageSize - 1), Me._RecordCount)

                PagerDisplay.Append("<b>" & Resources.Resource.DisplayingPage & "</b> ")
                PagerDisplay.Append(Me._DataPage.CurrentPageIndex + 1)
                PagerDisplay.Append(" <b>" & Resources.Resource.DisplayingOf & "</b> ")
                PagerDisplay.Append(Me._DataPage.PageCount & ",  ")
                PagerDisplay.Append(" <b>" & Resources.Resource.DisplayingRows & "</b> ")
                PagerDisplay.Append(PageStartRange)
                PagerDisplay.Append(" - ")
                PagerDisplay.Append(PageEndRange)
                PagerDisplay.Append(" <b>" & Resources.Resource.DisplayingOf & "</b> ")
                PagerDisplay.Append(Me._RecordCount)

                Me._PagerInfoLabel.Text = PagerDisplay.ToString

                If PageCount >= 1 Then
                    Me._PagingTopPanel.Visible = True
                    Me._PagingBottomPanel.Visible = True
                    Dim pages As ArrayList = New ArrayList

                    If PageNumber > 0 And PageCount > _PagesToDisplay Then
                        LowerLimit = PageNumber - _PagesToDisplay
                        If LowerLimit < 1 Then
                            LowerLimit = 0
                        End If
                        If LowerLimit > PageCount - _PagesToDisplay Then
                            LowerLimit = PageCount - _PagesToDisplay
                        End If
                    End If

                    LowerLimit = PageNumber

                    If LowerLimit > PageCount - _PagesToDisplay Then
                        LowerLimit = PageCount - (_PagesToDisplay - 1)
                    End If

                    If LowerLimit < 1 Then
                        LowerLimit = 1
                    End If

                    If (PageNumber + _PagesToDisplay) > PageCount Then
                        UpperLimit = PageCount
                    Else
                        UpperLimit = (PageNumber + _PagesToDisplay)
                    End If

                    Dim i As Integer = LowerLimit

                    While i <= UpperLimit
                        pages.Add((i).ToString)
                        System.Math.Min(System.Threading.Interlocked.Increment(i), i - 1)
                    End While

                    Me._RepeaterTop.DataSource = pages
                    Me._RepeaterTop.DataBind()
                    Me._RepeaterBottom.DataSource = pages
                    Me._RepeaterBottom.DataBind()
                Else
                    Me._PagingTopPanel.Visible = False
                    Me._PagingBottomPanel.Visible = False
                End If

                Me._PreviousTopLinkButton.Enabled = (Not _DataPage.IsFirstPage)
                Me._NextTopLinkButton.Enabled = (Not _DataPage.IsLastPage)
                Me._PreviousBottomLinkButton.Enabled = (Not _DataPage.IsFirstPage)
                Me._NextBottomLinkButton.Enabled = (Not _DataPage.IsLastPage)

            End If

        Catch ex As Exception
            Throw ex
        End Try

    End Sub

    Protected Sub GoToPrevious(ByVal sender As Object, ByVal e As EventArgs)
        If ViewState("PageNumber") Is Nothing OrElse Convert.ToInt32(ViewState("PageNumber")) = 0 Then
            PageNumber = 0
        Else
            PageNumber = Convert.ToInt32(ViewState("PageNumber")) - 1
        End If
        BindDataItems()
    End Sub

    Protected Sub GoToNext(ByVal sender As Object, ByVal e As EventArgs)
        If Convert.ToInt32(ViewState("PageNumber")) + 1 = PageCount Then
            PageNumber = PageCount - 1
        Else
            PageNumber = Convert.ToInt32(ViewState("PageNumber")) + 1
        End If
        BindDataItems()
    End Sub

    Protected Sub PagingRepeater_ItemCommand(ByVal sender As Object, ByVal e As RepeaterCommandEventArgs)
        PageNumber = Convert.ToInt32(e.CommandArgument) - 1
        BindDataItems()
    End Sub

    Protected Function BoldPageNumber(ByVal Item As String) As String
        If Convert.ToInt32(Item) - 1 = PageNumber Then
            Return "<b>" + Item + "</b>"
        Else
            Return Item
        End If
    End Function

#End Region

#End Region

#Region " Repeaters "

    Protected Overridable Overloads Sub uxForumChildRepeater_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs)
        Dim item As RepeaterItem = e.Item
        Dim Icon As System.Web.UI.WebControls.Image = CType(item.FindControl("uxStatusImage"), System.Web.UI.WebControls.Image)

        If (item.ItemType = ListItemType.Item) OrElse (item.ItemType = ListItemType.AlternatingItem) Then
            Icon.ImageUrl = String.Format("~/App_Themes/{0}/images/icons/topic.gif", Page.Theme.ToString)
        End If

    End Sub

#End Region

#Region " Methods "

    Protected Sub DisableAll(ByVal CTL As Control)
        For Each c As Control In CTL.Controls
            If c.GetType() Is GetType(TextBox) Then
                If Not (CType(c, TextBox).ID = "uxCommentsTextbox" Or CType(c, TextBox).ID = "uxCommentsSubjectTextBox") Then
                    CType(c, TextBox).Enabled = False
                End If
            End If

            If c.GetType() Is GetType(DropDownList) Then
                If Not CType(c, DropDownList).ID = "uxPageSizeDropDownList" Then 'Always allow page number list
                    CType(c, DropDownList).Enabled = False
                End If
            End If

            If c.GetType() Is GetType(Button) Then
                If Not (CType(c, Button).ID = "uxPreviewButton" Or CType(c, Button).ID = "uxSubmitCommentButton" Or (CType(c, Button).ID = "uxResetCommentButton")) Then
                    CType(c, Button).Enabled = False
                End If
            End If

            If c.GetType() Is GetType(TreeView) Then
                CType(c, TreeView).Enabled = False
            End If

            If c.GetType() Is GetType(GridView) Then
                'CType(c, GridView).Enabled = False
            Else
                DisableAll(c)
            End If
        Next
    End Sub

    Protected Sub EnableAll(ByVal CTL As Control)

        For Each c As Control In CTL.Controls
            If c.GetType() Is GetType(TextBox) Then
                CType(c, TextBox).Enabled = True
            End If

            If c.GetType() Is GetType(DropDownList) Then
                CType(c, DropDownList).Enabled = True
            End If

            If c.GetType() Is GetType(Button) Then
                CType(c, Button).Enabled = True
            End If

            If c.GetType() Is GetType(TreeView) Then
                CType(c, TreeView).Enabled = True
            End If

            If c.GetType() Is GetType(GridView) Then
                'CType(c, GridView).Enabled = True
            Else
                EnableAll(c)
            End If
        Next
    End Sub

    Protected Sub LoadAvatar(ByVal ImageCtl As WebControls.Image, ByVal UserName As String, ByVal EditProfile As Boolean)

        Dim PC As ProfileCommon = New ProfileCommon

        If Not (PC.GetProfile(UserName).User.Picture Is Nothing) Then

            If EditProfile Then
                If Not (PC.GetProfile(UserName).User.Picture Is Nothing) Then
                    ImageCtl.ImageUrl = String.Format("{0}.aspx?pid=cp_avatar&editprofile=1", AppPage)
                End If
            Else
                If Not (PC.GetProfile(UserName).User.Picture Is Nothing) Then
                    ImageCtl.ImageUrl = String.Format("{0}.aspx?pid=cp_avatar&showavatar=1&UserName={1}", AppPage, UserName)
                End If
            End If

        Else
            ImageCtl.ImageUrl = String.Format("{0}app_themes/{1}/images/noavatar.png", AppPath, Page.Theme)
        End If

    End Sub

    Protected Sub LoadThemeImage(ByVal ImageCtl As WebControls.Image, ByVal SelectedValue As String)

        If SelectedValue = DropDownDefaultGuidValue Then
            SelectedValue = "default"
        End If

        If File.Exists(String.Format("{0}App_Themes/{1}/images/preview.jpg", PhysicalAppPath, SelectedValue)) Then
            ImageCtl.ImageUrl = String.Format("{0}App_Themes/{1}/images/preview.jpg", AppPath, SelectedValue)
        Else
            ImageCtl.ImageUrl = String.Format("{0}app_themes/{1}/images/nopreview.jpg", AppPath, Page.Theme)
        End If
    End Sub

    Protected Sub SetPanelState(ByVal Ctl As Panel, ByVal Enabled As Boolean, ByVal Visible As Boolean)

        Ctl.Enabled = Enabled
        Ctl.Visible = Visible

    End Sub

    Protected Function GetRegularExpression(ByVal ValidationType As SecondaryValidatorTypes) As String

        Dim expression As String = String.Empty

        Select Case ValidationType
            Case SecondaryValidatorTypes.Email
                expression = EmailReGEx
            Case SecondaryValidatorTypes.NoSpaces
                expression = NoSpacesReGEx
            Case SecondaryValidatorTypes.NoSpacesLetters
                expression = NoSpacesLettersReGEx
            Case SecondaryValidatorTypes.NoSpacesNumbers
                expression = NoSpacesNumbersReGEx
            Case SecondaryValidatorTypes.Uppercase
                expression = UppercaseReGEx
            Case SecondaryValidatorTypes.Lowercase
                expression = LowercaseReGEx
            Case SecondaryValidatorTypes.NumbersOnly
                expression = NumbersOnlyReGEx
            Case SecondaryValidatorTypes.LettersOnly
                expression = LettersOnlyReGEx
            Case SecondaryValidatorTypes.WebAddress
                expression = WebAddressRegEx
        End Select

        Return expression

    End Function

#End Region

#Region " Form/Survey Page Builders "

#Region " Base Items "

    Protected Sub BuildPage(ByVal FormGuid As Guid, ByVal FormResponseGuid As Guid, ByVal ControlsPlaceholder As PlaceHolder, ByVal ValidationGroup As String, ByVal LoadAnswers As Boolean, ByVal LoadAnalysis As Boolean)
        Dim list As New FormList
        Dim DT As New DataTable
        Dim DR As DataRow

        DT = list.GetControls(FormGuid)

        ControlsPlaceholder.Controls.Clear()

        Dim table As New HtmlTable
        table.ID = "uxControlsTable"
        table.Width = "100%"

        If DT.Rows.Count > 0 Then
            For Each DR In DT.Rows

                Dim row As New HtmlTableRow
                Dim questionrow As New HtmlTableRow

                row.ID = String.Format("ux_{0}_TableRow", DR("formquestionid").ToString())
                questionrow.ID = String.Format("ux_{0}_TableHeaderRow", DR("formquestionid").ToString())

                questionrow.Cells.Add(BuildLabelCell(DR("formquestionid").ToString(), DR("question").ToString()))
                row.Cells.Add(BuildControlCell(DR("formquestionid").ToString(), FormResponseGuid, CType(DR("controltype"), FormControlType), ValidationGroup, LoadAnswers, LoadAnalysis))

                table.Rows.Add(questionrow)
                table.Rows.Add(row)
            Next
        End If

        ControlsPlaceholder.Controls.Add(table)

    End Sub

    Protected Function BuildLabelCell(ByVal FormQuestionID As String, ByVal Question As String) As HtmlTableCell

        Dim cell As New HtmlTableCell
        Dim lblQuestion As New Label

        lblQuestion.ID = String.Format("ux_{0}_Label", FormQuestionID)
        lblQuestion.Text = Question

        cell.Controls.Add(lblQuestion)

        cell.ID = String.Format("ux_{0}_LabelCell", FormQuestionID)
        cell.Attributes.Add("class", "TDNAME")
        Return cell

    End Function

    Protected Function BuildControlCell(ByVal FormQuestionID As String, ByVal FormResponseGuid As Guid, ByVal ControlType As FormControlType, ByVal ValidationGroup As String, ByVal LoadAnswers As Boolean, ByVal LoadAnalysis As Boolean) As HtmlTableCell

		Dim cell As New HtmlTableCell
        Dim QuestionDetail As FormQuestionDetail = FormQuestionDetail.GetFormQuestionDetail(ConvertToGuid(FormQuestionID))

        Select Case ControlType
            Case FormControlType.SingleTextBox

                BuildSingleTextBox(FormQuestionID, FormResponseGuid, ValidationGroup, LoadAnswers, cell, QuestionDetail, LoadAnalysis)

            Case FormControlType.MultilineTextBox

                BuildMultiLineTextBox(FormQuestionID, FormResponseGuid, ValidationGroup, LoadAnswers, cell, QuestionDetail, LoadAnalysis)

            Case FormControlType.SelectionList

                BuildSelectionList(FormQuestionID, FormResponseGuid, ValidationGroup, LoadAnswers, cell, QuestionDetail, LoadAnalysis)

            Case FormControlType.DateTimeBox

                BuildDataTimeBox(FormQuestionID, FormResponseGuid, ValidationGroup, LoadAnswers, cell, QuestionDetail, LoadAnalysis)

            Case FormControlType.MultipleChoiceSingleAnswer

                BuildMultipleChoiceSingleAnswer(FormQuestionID, FormResponseGuid, ValidationGroup, LoadAnswers, cell, QuestionDetail, LoadAnalysis)

            Case FormControlType.MultipleChoiceMultipleAnswer

                BuildMultipleChoiceMultipleAnswer(FormQuestionID, FormResponseGuid, ValidationGroup, LoadAnswers, cell, QuestionDetail, LoadAnalysis)

            Case FormControlType.MatrixOneAnswerPerRow

                BuildMatrixOneAnswerPerRow(FormQuestionID, FormResponseGuid, ValidationGroup, LoadAnswers, cell, QuestionDetail, LoadAnalysis)

            Case FormControlType.MatrixMultipleAnswersPerRow

                BuildMatrixMultipleAnswersPerRow(FormQuestionID, FormResponseGuid, ValidationGroup, LoadAnswers, cell, QuestionDetail, LoadAnalysis)

        End Select

		cell.ID = String.Format("ux_{0}_ControlCell", FormQuestionID)

		If Not LoadAnalysis Then
			cell.Attributes.Add("class", "TDVALUE")
		End If

        Return cell

    End Function

#End Region

#Region " Build Controls "

#Region " Text Controls "

	Protected Sub BuildSingleTextBox(ByVal FormQuestionID As String, ByVal FormResponseGuid As Guid, ByVal ValidationGroup As String, ByVal LoadAnswers As Boolean, ByVal cell As HtmlTableCell, ByVal QuestionDetail As FormQuestionDetail, ByVal LoadAnalysis As Boolean)

		If LoadAnalysis Then

			BuildTextAnalysisView(FormQuestionID, cell)

		Else

			Dim stb As New TextBox

			stb.ID = String.Format("ux_{0}_TextBox", FormQuestionID)
			stb.Width = New Unit(95, UnitType.Percentage)

			If LoadAnswers Then
				Dim AnswerDetail As FormAnswerDetail = FormAnswerDetail.GetFormAnswerDetail(ConvertToGuid(FormQuestionID), FormResponseGuid)
				stb.Text = AnswerDetail.Answer.Trim()
			End If

			cell.Controls.Add(stb)

			If QuestionDetail.IsRequired Then
				cell.Controls.Add(BuildRequiredFieldValidator(stb.ClientID, QuestionDetail.RequiredText, ValidationGroup, ValidatorDisplay.Dynamic))
			End If

			If QuestionDetail.IsCompareValidatorRequired Then
				cell.Controls.Add(BuildCompareFieldValidator(stb.ClientID, QuestionDetail.CompareValidatorText, ValidationGroup, ValidatorDisplay.Dynamic, CType(QuestionDetail.CompareValidatorType, ValidationDataType)))
			End If

			If QuestionDetail.IsRegularExpressionValidatorRequired Then
				cell.Controls.Add(BuildRegularExpressionValidator(stb.ClientID, QuestionDetail.RegularExpressionValidatorText, ValidationGroup, ValidatorDisplay.Dynamic, QuestionDetail.RegularExpression))
			End If

			If QuestionDetail.IsRangeValidatorRequired Then
				cell.Controls.Add(BuildRangeValidator(stb.ClientID, QuestionDetail.RangeValidatorText, ValidationGroup, ValidatorDisplay.Dynamic, QuestionDetail.RangeStart, QuestionDetail.RangeEnd))
			End If

		End If

	End Sub

	Protected Sub BuildMultiLineTextBox(ByVal FormQuestionID As String, ByVal FormResponseGuid As Guid, ByVal ValidationGroup As String, ByVal LoadAnswers As Boolean, ByVal cell As HtmlTableCell, ByVal QuestionDetail As FormQuestionDetail, ByVal LoadAnalysis As Boolean)

		If LoadAnalysis Then

			BuildTextAnalysisView(FormQuestionID, cell)

		Else

			Dim mtb As New TextBox

			mtb.ID = String.Format("ux_{0}_TextBox", FormQuestionID)
			mtb.TextMode = TextBoxMode.MultiLine
			mtb.Rows = QuestionDetail.FormControlRows
			mtb.Columns = QuestionDetail.FormControlCols

			If LoadAnswers Then
				Dim AnswerDetail As FormAnswerDetail = FormAnswerDetail.GetFormAnswerDetail(ConvertToGuid(FormQuestionID), FormResponseGuid)
				mtb.Text = AnswerDetail.Answer.Trim()
			End If

			cell.Controls.Add(mtb)

			If QuestionDetail.IsRequired Then
				cell.Controls.Add(BuildRequiredFieldValidator(mtb.ClientID, QuestionDetail.RequiredText, ValidationGroup, ValidatorDisplay.Dynamic))
			End If

			If QuestionDetail.IsCompareValidatorRequired Then
				cell.Controls.Add(BuildCompareFieldValidator(mtb.ClientID, QuestionDetail.CompareValidatorText, ValidationGroup, ValidatorDisplay.Dynamic, CType(QuestionDetail.CompareValidatorType, ValidationDataType)))
			End If

			If QuestionDetail.IsRegularExpressionValidatorRequired Then
				cell.Controls.Add(BuildRegularExpressionValidator(mtb.ClientID, QuestionDetail.RegularExpressionValidatorText, ValidationGroup, ValidatorDisplay.Dynamic, QuestionDetail.RegularExpression))
			End If

			If QuestionDetail.IsRangeValidatorRequired Then
				cell.Controls.Add(BuildRangeValidator(mtb.ClientID, QuestionDetail.RangeValidatorText, ValidationGroup, ValidatorDisplay.Dynamic, QuestionDetail.RangeStart, QuestionDetail.RangeEnd))
			End If

		End If
	End Sub

	Protected Sub BuildDataTimeBox(ByVal FormQuestionID As String, ByVal FormResponseGuid As Guid, ByVal ValidationGroup As String, ByVal LoadAnswers As Boolean, ByVal cell As HtmlTableCell, ByVal QuestionDetail As FormQuestionDetail, ByVal LoadAnalysis As Boolean)

		If LoadAnalysis Then

			BuildTextAnalysisView(FormQuestionID, cell)

		Else

			Dim stb As New TextBox
			Dim calimage As System.Web.UI.WebControls.Image = BuildCalendarImage(FormQuestionID)

			stb.ID = String.Format("ux_{0}_DateTextBox", FormQuestionID)
			stb.Width = New Unit(75, UnitType.Pixel)

			If LoadAnswers Then
				Dim AnswerDetail As FormAnswerDetail = FormAnswerDetail.GetFormAnswerDetail(ConvertToGuid(FormQuestionID), FormResponseGuid)

				If Not String.IsNullOrEmpty(AnswerDetail.Answer) Then
					stb.Text = Convert.ToDateTime(AnswerDetail.Answer).ToShortDateString().Trim()
				End If

			End If

			cell.Controls.Add(stb)
			cell.Controls.Add(BuildSpacerImage(FormQuestionID))
			cell.Controls.Add(calimage)
			cell.Controls.Add(BuildCalendarExtender(FormQuestionID, stb.ClientID, calimage.ClientID))

			If QuestionDetail.IsRequired Then
				cell.Controls.Add(BuildRequiredFieldValidator(stb.ClientID, QuestionDetail.RequiredText, ValidationGroup, ValidatorDisplay.Dynamic))
			End If

			If QuestionDetail.IsCompareValidatorRequired Then
				cell.Controls.Add(BuildCompareFieldValidator(stb.ClientID, QuestionDetail.CompareValidatorText, ValidationGroup, ValidatorDisplay.Dynamic, CType(QuestionDetail.CompareValidatorType, ValidationDataType)))
			Else
				cell.Controls.Add(BuildCompareFieldValidator(stb.ClientID, "Please enter a valid date format.", ValidationGroup, ValidatorDisplay.Dynamic, ValidationDataType.Date))
			End If

			If QuestionDetail.IsRegularExpressionValidatorRequired Then
				cell.Controls.Add(BuildRegularExpressionValidator(stb.ClientID, QuestionDetail.RegularExpressionValidatorText, ValidationGroup, ValidatorDisplay.Dynamic, QuestionDetail.RegularExpression))
			End If

			If QuestionDetail.IsRangeValidatorRequired Then
				cell.Controls.Add(BuildRangeValidator(stb.ClientID, QuestionDetail.RangeValidatorText, ValidationGroup, ValidatorDisplay.Dynamic, QuestionDetail.RangeStart, QuestionDetail.RangeEnd))
			End If

		End If
	End Sub

	Private Sub BuildTextAnalysisView(ByVal FormQuestionID As String, ByVal cell As HtmlTableCell)
		Dim item As FormResults = New FormResults()

		item.GetFormResult(ConvertToGuid(FormQuestionID))

		Dim tableresults As New Table
		tableresults.ID = GenerateID()
		tableresults.Width = New Unit(100, UnitType.Percentage)
		tableresults.SkinID = "FORM_SURVEY_RESULTS_TABLE"

		Dim rowheader As New TableRow
		rowheader.ID = GenerateID()

		Dim cellresults As New TableCell
		Dim cellresponses As New TableCell

		cellresults.ID = GenerateID()
		cellresponses.ID = GenerateID()

		cellresults.Width = New Unit(80, UnitType.Percentage)
		cellresponses.Width = New Unit(20, UnitType.Percentage)

		cellresults.SkinID = "FORM_SURVEY_RESULTS_HEADER_TABLECELL"
		cellresponses.SkinID = "FORM_SURVEY_RESULTS_HEADER_TABLECELL"

		cellresults.Controls.Add(BuildLabel(GenerateID(), String.Empty))
		cellresponses.Controls.Add(BuildLabel(GenerateID(), "Responses"))

		rowheader.Cells.Add(cellresults)
		rowheader.Cells.Add(cellresponses)

		tableresults.Rows.Add(rowheader)

		Dim tablerow As New TableRow
		tablerow.ID = GenerateID()

		Dim viewcell As New TableCell
		Dim responsecell As New TableCell

		viewcell.ID = GenerateID()
		responsecell.ID = GenerateID()

		viewcell.Width = New Unit(80, UnitType.Percentage)
		responsecell.Width = New Unit(20, UnitType.Percentage)

		viewcell.SkinID = "FORM_SURVEY_RESULTS_ITEM_TABLECELL"
		viewcell.HorizontalAlign = HorizontalAlign.Right
		responsecell.SkinID = "FORM_SURVEY_RESULTS_ITEM_TABLECELL"

		viewcell.Controls.Add(BuildTextAnswerList(FormQuestionID))
		responsecell.Controls.Add(BuildLabel(GenerateID(), item.AnswerCount))

		tablerow.Cells.Add(viewcell)
		tablerow.Cells.Add(responsecell)

		tableresults.Rows.Add(tablerow)

		cell.Controls.Add(tableresults)

	End Sub

	Private Function BuildTextAnswerList(ByVal FormQuestionID As String) As Table
		Dim table As New Table
		Dim tablebutton As New Table
		Dim row As New TableRow
		Dim rowbutton As New TableRow
		Dim cell As New TableCell
		Dim cellbutton As New TableCell
		Dim panel As New Panel
		Dim popup As New AjaxControlToolkit.ModalPopupExtender
		Dim closebtn As New Button
		Dim viewbtn As New Button

		table.ID = GenerateID()
		row.ID = GenerateID()
		cell.ID = GenerateID()
		tablebutton.ID = GenerateID()
		rowbutton.ID = GenerateID()
		cellbutton.ID = GenerateID()

		panel.ID = String.Format("ux_{0}_TextAnswerPanel", FormQuestionID)
		popup.ID = String.Format("ux_{0}_TextAnswerPopUpExtender", FormQuestionID)
		closebtn.ID = String.Format("ux_{0}_CloseButton", FormQuestionID)
		viewbtn.ID = String.Format("ux_{0}_ViewButton", FormQuestionID)

		panel.CssClass = "MODALPOPUP"
		panel.Style.Add("display", "none")

		popup.BackgroundCssClass = "MODALBACKGROUND"

		closebtn.CssClass = "BUTTON"
		closebtn.Attributes.Add("onmouseover", "this.className='BUTTONOVER'")
		closebtn.Attributes.Add("onmouseout", "this.className='BUTTONOUT'")

		viewbtn.CssClass = "BUTTON"
		viewbtn.Attributes.Add("onmouseover", "this.className='BUTTONOVER'")
		viewbtn.Attributes.Add("onmouseout", "this.className='BUTTONOUT'")

		closebtn.Text = Resources.Resource.Close
		viewbtn.Text = "View"

		cellbutton.Controls.Add(closebtn)
		cellbutton.HorizontalAlign = HorizontalAlign.Center

		rowbutton.Cells.Add(cellbutton)

		tablebutton.Rows.Add(rowbutton)
		tablebutton.Width = New Unit(100, UnitType.Percentage)

		panel.Controls.Add(CreateDataGrid(FormQuestionID))
		panel.Controls.Add(tablebutton)
		popup.TargetControlID = viewbtn.ClientID
		popup.PopupControlID = panel.ClientID
		popup.CancelControlID = closebtn.ClientID

		cell.Controls.Add(viewbtn)
		cell.Controls.Add(panel)
		cell.Controls.Add(popup)
		cell.HorizontalAlign = HorizontalAlign.Left

		row.Cells.Add(cell)
		table.Rows.Add(row)
		table.Width = New Unit(100, UnitType.Percentage)

		Return table
	End Function

	Private Function CreateDataGrid(ByVal FormQuestionID As String) As GridView
		Try
			Dim gv As New GridView()
			gv.ID = String.Format("ux_{0}_AnswerTextGridView", FormQuestionID)

			gv.CellPadding = 2
			gv.ForeColor = ColorTranslator.FromHtml("#333333")
			gv.GridLines = GridLines.Both
			gv.AllowPaging = True
			gv.AutoGenerateColumns = False
			gv.RowStyle.BackColor = ColorTranslator.FromHtml("#F7F6F3")
			gv.RowStyle.ForeColor = ColorTranslator.FromHtml("#333333")
			gv.RowStyle.Font.Size = New FontUnit(10, UnitType.Pixel)
			gv.AlternatingRowStyle.BackColor = Color.White
			gv.AlternatingRowStyle.ForeColor = ColorTranslator.FromHtml("#284775")
			gv.AlternatingRowStyle.Font.Size = New FontUnit(10, UnitType.Pixel)
			gv.Width = New Unit(98, UnitType.Percentage)

			Dim answer As New TemplateField()
			Dim responseid As New TemplateField()
			Dim responsebtn As New TemplateField()

			answer.ItemTemplate = New GridViewTemplate(ListItemType.Item, "Answer", GridViewTemplate.ItemType.Label)
			answer.HeaderTemplate = New GridViewTemplate(ListItemType.Header, "Answer", GridViewTemplate.ItemType.Header)

			responseid.ItemTemplate = New GridViewTemplate(ListItemType.Item, "FormResponseID", GridViewTemplate.ItemType.Label)
			responseid.Visible = False

			responsebtn.ItemTemplate = New GridViewTemplate(ListItemType.Item, "FormResponseID", GridViewTemplate.ItemType.Display)

			gv.Columns.Add(responseid)
			gv.Columns.Add(responsebtn)
			gv.Columns.Add(answer)

			Dim list As FormList = New FormList()
			gv.DataSource = list.GetTextAnswers(ConvertToGuid(FormQuestionID))
			gv.DataBind()

			Return gv
		Catch ex As Exception
			Return New GridView()
		End Try
	End Function

	Protected Sub BuildOptionalTextBox(ByVal FormQuestionID As String, ByVal FormResponseGuid As Guid, ByVal ValidationGroup As String, ByVal LoadAnswers As Boolean, ByVal cell As HtmlTableCell, ByVal QuestionDetail As FormQuestionDetail, ByVal LoadAnalysis As Boolean)

		If LoadAnalysis Then

			'BuildTextAnalysisView(FormQuestionID, cell)

		Else

			Dim otb As New TextBox

			otb.ID = String.Format("ux_{0}_OptionalTextBox", FormQuestionID)
			otb.Width = New Unit(95, UnitType.Percentage)

			'If LoadAnswers Then
			'	Dim AnswerDetail As FormAnswerDetail = FormAnswerDetail.GetFormAnswerDetail(ConvertToGuid(FormQuestionID), FormResponseGuid)
			'	otb.Text = AnswerDetail.Answer.Trim()
			'End If

			cell.Controls.Add(otb)

		End If

	End Sub

#End Region

#Region " Choice Controls "

	Protected Sub BuildSelectionList(ByVal FormQuestionID As String, ByVal FormResponseGuid As Guid, ByVal ValidationGroup As String, ByVal LoadAnswers As Boolean, ByVal cell As HtmlTableCell, ByVal QuestionDetail As FormQuestionDetail, ByVal LoadAnalysis As Boolean)

		If LoadAnalysis Then

			BuildChoiceAnalysisView(FormQuestionID, cell)

		Else

			Dim ddl As New DropDownList
			Dim list As New FormList()

			ddl.ID = String.Format("ux_{0}_DropDownList", FormQuestionID)
			ddl.DataSource = list.GetQuestionRows(ConvertToGuid(FormQuestionID))
			ddl.DataTextField = "RowChoice"
			ddl.DataValueField = "FormRowID"
			ddl.DataBind()

			If LoadAnswers Then

				ddl.Enabled = False

				Dim li As New ListItem

				For Each li In ddl.Items
					Dim MultiItem As FormAnswerRowColumnDetail = FormAnswerRowColumnDetail.GetFormAnswerRowColumnDetail(ConvertToGuid(FormQuestionID), FormResponseGuid, ConvertToGuid(li.Value.ToString()))
					If MultiItem.HasData Then
						If MultiItem.IsSelected Then
							li.Selected = True
						End If
					End If
				Next

			End If

			cell.Controls.Add(ddl)

			If QuestionDetail.IsRequired Then
				cell.Controls.Add(BuildRequiredFieldValidator(ddl.ClientID, QuestionDetail.RequiredText, ValidationGroup, ValidatorDisplay.Dynamic))
			End If

			If QuestionDetail.IsCompareValidatorRequired Then
				cell.Controls.Add(BuildCompareFieldValidator(ddl.ClientID, QuestionDetail.CompareValidatorText, ValidationGroup, ValidatorDisplay.Dynamic, CType(QuestionDetail.CompareValidatorType, ValidationDataType)))
			End If

			If QuestionDetail.IsRegularExpressionValidatorRequired Then
				cell.Controls.Add(BuildRegularExpressionValidator(ddl.ClientID, QuestionDetail.RegularExpressionValidatorText, ValidationGroup, ValidatorDisplay.Dynamic, QuestionDetail.RegularExpression))
			End If

			If QuestionDetail.IsRangeValidatorRequired Then
				cell.Controls.Add(BuildRangeValidator(ddl.ClientID, QuestionDetail.RangeValidatorText, ValidationGroup, ValidatorDisplay.Dynamic, QuestionDetail.RangeStart, QuestionDetail.RangeEnd))
			End If

		End If
	End Sub

	Protected Sub BuildMultipleChoiceSingleAnswer(ByVal FormQuestionID As String, ByVal FormResponseGuid As Guid, ByVal ValidationGroup As String, ByVal LoadAnswers As Boolean, ByVal cell As HtmlTableCell, ByVal QuestionDetail As FormQuestionDetail, ByVal LoadAnalysis As Boolean)

		If LoadAnalysis Then

			BuildChoiceAnalysisView(FormQuestionID, cell)

			If QuestionDetail.IsOtherOption Then
				If LoadAnalysis Then
					BuildTextAnalysisView(FormQuestionID, cell)
				End If
			End If

		Else

			Dim rbl As New RadioButtonList
			Dim list As New FormList()

			rbl.ID = String.Format("ux_{0}_RadioButtonList", FormQuestionID)
			rbl.RepeatDirection = CType(QuestionDetail.FormControlLayout, RepeatDirection)
			rbl.RepeatLayout = RepeatLayout.Table
			rbl.DataSource = list.GetQuestionRows(ConvertToGuid(FormQuestionID))
			rbl.DataTextField = "RowChoice"
			rbl.DataValueField = "FormRowID"
			rbl.DataBind()

			If LoadAnswers Then

				rbl.Enabled = False

				Dim li As New ListItem

				For Each li In rbl.Items
					Dim MultiItem As FormAnswerRowColumnDetail = FormAnswerRowColumnDetail.GetFormAnswerRowColumnDetail(ConvertToGuid(FormQuestionID), FormResponseGuid, ConvertToGuid(li.Value.ToString()))
					If MultiItem.HasData Then
						If MultiItem.IsSelected Then
							li.Selected = True
						End If
					End If
				Next

			End If

			cell.Controls.Add(rbl)

			If QuestionDetail.IsRequired Then
				cell.Controls.Add(BuildRadioButtonListRequiredFieldValidator(rbl.ClientID, QuestionDetail.RequiredText, ValidationGroup, ValidatorDisplay.Dynamic))
			End If

			If QuestionDetail.IsOtherOption Then

				Dim otb As New TextBox

				otb.ID = String.Format("ux_{0}_OptionalTextBox", FormQuestionID)
				otb.Width = New Unit(95, UnitType.Percentage)

				If LoadAnswers Then
					Dim AnswerDetail As FormAnswerDetail = FormAnswerDetail.GetFormAnswerDetail(ConvertToGuid(FormQuestionID), FormResponseGuid)
					otb.Text = AnswerDetail.Answer.Trim()
				End If

				cell.Controls.Add(otb)
				cell.Controls.Add(BuildRadioButtonDependantControlValidator(rbl.ClientID, QuestionDetail.RequiredText, ValidationGroup, ValidatorDisplay.Dynamic, QuestionDetail.OtherOptionText, otb.ClientID, CheckBoxListDependantControlValidator.TargetControlType.TextBox))

			End If

			If QuestionDetail.IsCompareValidatorRequired Then
				cell.Controls.Add(BuildCompareFieldValidator(rbl.ClientID, QuestionDetail.CompareValidatorText, ValidationGroup, ValidatorDisplay.Dynamic, CType(QuestionDetail.CompareValidatorType, ValidationDataType)))
			End If

			If QuestionDetail.IsRegularExpressionValidatorRequired Then
				cell.Controls.Add(BuildRegularExpressionValidator(rbl.ClientID, QuestionDetail.RegularExpressionValidatorText, ValidationGroup, ValidatorDisplay.Dynamic, QuestionDetail.RegularExpression))
			End If

			If QuestionDetail.IsRangeValidatorRequired Then
				cell.Controls.Add(BuildRangeValidator(rbl.ClientID, QuestionDetail.RangeValidatorText, ValidationGroup, ValidatorDisplay.Dynamic, QuestionDetail.RangeStart, QuestionDetail.RangeEnd))
			End If

		End If
	End Sub

	Protected Sub BuildMultipleChoiceMultipleAnswer(ByVal FormQuestionID As String, ByVal FormResponseGuid As Guid, ByVal ValidationGroup As String, ByVal LoadAnswers As Boolean, ByVal cell As HtmlTableCell, ByVal QuestionDetail As FormQuestionDetail, ByVal LoadAnalysis As Boolean)

		If LoadAnalysis Then

			BuildChoiceAnalysisView(FormQuestionID, cell)

			If QuestionDetail.IsOtherOption Then
				If LoadAnalysis Then
					BuildTextAnalysisView(FormQuestionID, cell)
				End If
			End If

		Else

			Dim cbl As New CheckBoxList
			Dim list As New FormList()

			cbl.ID = String.Format("ux_{0}_CheckBoxList", FormQuestionID)
			cbl.RepeatDirection = CType(QuestionDetail.FormControlLayout, RepeatDirection)
			cbl.RepeatLayout = RepeatLayout.Table
			cbl.DataSource = list.GetQuestionRows(ConvertToGuid(FormQuestionID))
			cbl.DataTextField = "RowChoice"
			cbl.DataValueField = "FormRowID"
			cbl.DataBind()

			If LoadAnswers Then

				cbl.Enabled = False

				Dim li As New ListItem

				For Each li In cbl.Items
					Dim MultiItem As FormAnswerRowColumnDetail = FormAnswerRowColumnDetail.GetFormAnswerRowColumnDetail(ConvertToGuid(FormQuestionID), FormResponseGuid, ConvertToGuid(li.Value.ToString()))
					If MultiItem.HasData Then
						If MultiItem.IsSelected Then
							li.Selected = True
						End If
					End If
				Next
			End If

			cell.Controls.Add(cbl)

			If QuestionDetail.IsRequired Then
				cell.Controls.Add(BuildCheckBoxListRequiredFieldValidator(cbl.ClientID, QuestionDetail.RequiredText, ValidationGroup, ValidatorDisplay.Dynamic))
			End If

			If QuestionDetail.IsOtherOption Then

				Dim otb As New TextBox

				otb.ID = String.Format("ux_{0}_OptionalTextBox", FormQuestionID)
				otb.Width = New Unit(95, UnitType.Percentage)

				If LoadAnswers Then
					Dim AnswerDetail As FormAnswerDetail = FormAnswerDetail.GetFormAnswerDetail(ConvertToGuid(FormQuestionID), FormResponseGuid)
					otb.Text = AnswerDetail.Answer.Trim()
				End If

				cell.Controls.Add(otb)
				cell.Controls.Add(BuildCheckBoxListDependantControlValidator(cbl.ClientID, QuestionDetail.RequiredText, ValidationGroup, ValidatorDisplay.Dynamic, QuestionDetail.OtherOptionText, otb.ClientID, CheckBoxListDependantControlValidator.TargetControlType.TextBox))

			End If

			If QuestionDetail.IsCompareValidatorRequired Then
				cell.Controls.Add(BuildCompareFieldValidator(cbl.ClientID, QuestionDetail.CompareValidatorText, ValidationGroup, ValidatorDisplay.Dynamic, CType(QuestionDetail.CompareValidatorType, ValidationDataType)))
			End If

			If QuestionDetail.IsRegularExpressionValidatorRequired Then
				cell.Controls.Add(BuildRegularExpressionValidator(cbl.ClientID, QuestionDetail.RegularExpressionValidatorText, ValidationGroup, ValidatorDisplay.Dynamic, QuestionDetail.RegularExpression))
			End If

			If QuestionDetail.IsRangeValidatorRequired Then
				cell.Controls.Add(BuildRangeValidator(cbl.ClientID, QuestionDetail.RangeValidatorText, ValidationGroup, ValidatorDisplay.Dynamic, QuestionDetail.RangeStart, QuestionDetail.RangeEnd))
			End If

		End If
	End Sub

	Private Sub BuildChoiceAnalysisView(ByVal FormQuestionID As String, ByVal cell As HtmlTableCell)

		Dim list As FormList = New FormList()

		Dim DT As New DataTable
		DT = list.GetQuestionRows(ConvertToGuid(FormQuestionID))

		If DT.Rows.Count > 0 Then
			Dim row As DataRow

			Dim tableresults As New Table
			tableresults.ID = GenerateID()
			tableresults.Width = New Unit(100, UnitType.Percentage)
			tableresults.SkinID = "FORM_SURVEY_RESULTS_TABLE"

			Dim rowheader As New TableRow
			rowheader.ID = GenerateID()

			Dim cellanswers As New TableCell
			Dim cellresults As New TableCell
			Dim cellpercent As New TableCell
			Dim cellresponses As New TableCell

			cellanswers.ID = GenerateID()
			cellresults.ID = GenerateID()
			cellpercent.ID = GenerateID()
			cellresponses.ID = GenerateID()

			cellanswers.SkinID = "FORM_SURVEY_RESULTS_HEADER_TABLECELL"
			cellresults.SkinID = "FORM_SURVEY_RESULTS_HEADER_TABLECELL"
			cellpercent.SkinID = "FORM_SURVEY_RESULTS_HEADER_TABLECELL"
			cellresponses.SkinID = "FORM_SURVEY_RESULTS_HEADER_TABLECELL"

			cellanswers.Controls.Add(BuildLabel(GenerateID(), "Answers"))
			cellresults.Controls.Add(BuildLabel(GenerateID(), "Results"))
			cellpercent.Controls.Add(BuildLabel(GenerateID(), "Percentage"))
			cellresponses.Controls.Add(BuildLabel(GenerateID(), "Responses"))

			rowheader.Cells.Add(cellanswers)
			rowheader.Cells.Add(cellresults)
			rowheader.Cells.Add(cellpercent)
			rowheader.Cells.Add(cellresponses)

			tableresults.Rows.Add(rowheader)

			For Each row In DT.Rows
				Dim tablerow As New TableRow
				tablerow.ID = GenerateID()

				Dim choicecell As New TableCell
				Dim tablecell As New TableCell
				Dim percentcell As New TableCell
				Dim responsecell As New TableCell

				choicecell.ID = GenerateID()
				tablecell.ID = GenerateID()
				percentcell.ID = GenerateID()
				responsecell.ID = GenerateID()

				choicecell.SkinID = "FORM_SURVEY_RESULTS_ITEM_TABLECELL"
				tablecell.SkinID = "FORM_SURVEY_RESULTS_ITEMGRAPH_TABLECELL"
				percentcell.SkinID = "FORM_SURVEY_RESULTS_ITEM_TABLECELL"
				responsecell.SkinID = "FORM_SURVEY_RESULTS_ITEM_TABLECELL"

				Dim item As FormResults = New FormResults()
				item.GetFormChoiceResult(ConvertToGuid(FormQuestionID), ConvertToGuid(row("FormRowID").ToString()))

				Dim FRD As FormQuestionRowsDetail = FormQuestionRowsDetail.GetFormQuestionRowsDetail(ConvertToGuid(row("FormRowID").ToString()))

				Dim tablegraph As New Table
				tablegraph.ID = GenerateID()
				tablegraph.SkinID = "FORM_SURVEY_RESULTS_GRAPH_TABLE"
				tablegraph.Width = New Unit(GetResultPercentage(item.AnswerCount, item.Divisor), UnitType.Percentage)

				Dim rowgraph As New TableRow
				rowgraph.ID = GenerateID()

				Dim cellgraph As New TableCell
				cellgraph.ID = GenerateID()
				cellgraph.SkinID = "FORM_SURVEY_RESULTS_GRAPH_TABLECELL"
				cellgraph.Controls.Add(BuildSpacerImage(GenerateID()))

				rowgraph.Cells.Add(cellgraph)

				tablegraph.Rows.Add(rowgraph)

				choicecell.Controls.Add(BuildLabel(GenerateID(), FRD.RowChoice.ToString()))
				tablecell.Controls.Add(tablegraph)
				percentcell.Controls.Add(BuildLabel(GenerateID(), FormatResultPercentage(GetResultPercentage(item.AnswerCount, item.Divisor))))
				responsecell.Controls.Add(BuildLabel(GenerateID(), item.AnswerCount))

				tablerow.Cells.Add(choicecell)
				tablerow.Cells.Add(tablecell)
				tablerow.Cells.Add(percentcell)
				tablerow.Cells.Add(responsecell)

				tableresults.Rows.Add(tablerow)

			Next

			cell.Controls.Add(tableresults)

		End If
	End Sub

#End Region

#Region " Build Matrix Controls "

	Protected Sub BuildMatrixOneAnswerPerRow(ByVal FormQuestionID As String, ByVal FormResponseGuid As Guid, ByVal ValidationGroup As String, ByVal LoadAnswers As Boolean, ByVal cell As HtmlTableCell, ByVal QuestionDetail As FormQuestionDetail, ByVal LoadAnalysis As Boolean)
		Dim list As New FormList()
		Dim DTColumns As New DataTable()
		Dim DTRows As New DataTable()
		Dim DRCols As DataRow
		Dim DRRows As DataRow

		DTColumns = list.GetQuestionColumns(ConvertToGuid(FormQuestionID))
		DTRows = list.GetQuestionRows(ConvertToGuid(FormQuestionID))

		Dim table As New Table
		Dim tableAnalysis As New Table
		Dim rowheader As New TableRow
		Dim cellheader As New TableCell

		table.ID = String.Format("ux_{0}_MatrixRadioButtonTable", FormQuestionID)
		rowheader.ID = String.Format("ux_{0}_MatrixRowHeader", FormQuestionID)
		cellheader.ID = String.Format("ux_{0}_MatrixCellHeader", FormQuestionID)

		tableAnalysis.ID = GenerateID()
		tableAnalysis.SkinID = "FORM_SURVEY_RESULTS_TABLE"

		If LoadAnalysis Then
			cellheader.SkinID = "FORM_SURVEY_RESULTS_HEADER_TABLECELL"
		End If

		cellheader.Controls.Add(BuildLabel(GenerateID(), String.Empty))

		rowheader.Cells.Add(cellheader)

		For Each DRCols In DTColumns.Rows
			Dim cellAnalysis As New TableCell
			cellAnalysis.ID = GenerateID()

			If LoadAnalysis Then
				cellAnalysis.SkinID = "FORM_SURVEY_RESULTS_HEADER_TABLECELL"
			End If

			cellAnalysis.Controls.Add(BuildLabel(GenerateID(), DRCols("ColumnChoice").ToString()))

			rowheader.Cells.Add(cellAnalysis)

		Next

		If LoadAnalysis Then
			Dim cellResponses As New TableCell
			cellResponses.ID = GenerateID()
			cellResponses.SkinID = "FORM_SURVEY_RESULTS_HEADER_TABLECELL"
			cellResponses.Controls.Add(BuildLabel(GenerateID(), "Responses"))
			rowheader.Cells.Add(cellResponses)
		End If

		If LoadAnalysis Then
			tableAnalysis.Rows.Add(rowheader)
		Else
			table.Rows.Add(rowheader)
		End If

		For Each DRRows In DTRows.Rows
			Dim rowchoice As New TableRow
			Dim cellChoice As New TableCell
			cellChoice.ID = GenerateID()

			Dim ResponseCount As Integer = 0

			If LoadAnalysis Then
				cellChoice.SkinID = "FORM_SURVEY_RESULTS_ITEM_TABLECELL"			
			End If

			rowchoice.ID = String.Format("ux_{0}_RowChoice", DRRows("FormRowID"))
			cellChoice.Controls.Add(BuildLabel(GenerateID(), DRRows("RowChoice").ToString()))
			rowchoice.Cells.Add(cellChoice)

			For Each DRCols In DTColumns.Rows
				If LoadAnalysis Then

					Dim item As FormList = New FormList()

					Dim DT As New DataTable

					DT = item.GetMatrixSingleAnswerResults(ConvertToGuid(FormQuestionID), ConvertToGuid(DRRows("FormRowID").ToString()), ConvertToGuid(DRCols("FormColumnID").ToString()))

					Dim cellChoiceAnalysis As New TableCell
					cellChoiceAnalysis.ID = GenerateID()
					cellChoiceAnalysis.SkinID = "FORM_SURVEY_RESULTS_ITEM_TABLECELL"

					If DT.Rows.Count > 0 Then
						Dim row As DataRow

						For Each row In DT.Rows

							cellChoiceAnalysis.Controls.Add(BuildLabel(String.Format("{0}", Guid.NewGuid()), FormatResultPercentage(GetResultPercentage(row("answercount"), row("divisor")))))							
							rowchoice.Cells.Add(cellChoiceAnalysis)

							ResponseCount += Convert.ToInt64(row("answercount").ToString())
						Next

					Else
						cellChoiceAnalysis.Controls.Add(BuildLabel(String.Format("{0}", Guid.NewGuid()), FormatResultPercentage(0)))

						rowchoice.Cells.Add(cellChoiceAnalysis)
					End If

				Else

					If LoadAnswers Then

						Dim rdb As RadioButton

						rdb = BuildRadioButton(String.Format("{0}_{1}_{2}", FormQuestionID, DRRows("FormRowID"), DRCols("FormColumnID").ToString()), String.Empty, DRRows("FormRowID").ToString())

						Dim fl As New FormList
						Dim DT As New DataTable

						DT = fl.GetAnswersForRowsColumns(ConvertToGuid(FormQuestionID), FormResponseGuid, ConvertToGuid(DRRows("FormRowID").ToString), ConvertToGuid(DRCols("FormColumnID").ToString()))

						If DT.Rows.Count > 0 Then
							rdb.Checked = True
						End If

						rdb.Enabled = False

						rowchoice.Cells.Add(BuildCell(String.Format("{0}_{1}", DRRows("FormRowID"), DRCols("FormColumnID").ToString()), rdb))
					Else
						rowchoice.Cells.Add(BuildCell(String.Format("{0}_{1}", DRRows("FormRowID"), DRCols("FormColumnID").ToString()), BuildRadioButton(String.Format("{0}_{1}_{2}", FormQuestionID, DRRows("FormRowID"), DRCols("FormColumnID").ToString()), String.Empty, DRRows("FormRowID").ToString())))
					End If

				End If
			Next

			If LoadAnalysis Then
				Dim cellChoiceResponses As New TableCell
				cellChoiceResponses.ID = GenerateID()
				cellChoiceResponses.SkinID = "FORM_SURVEY_RESULTS_ITEM_TABLECELL"
				cellChoiceResponses.Controls.Add(BuildLabel(String.Format("{0}", Guid.NewGuid()), ResponseCount))

				rowchoice.Cells.Add(cellChoiceResponses)
			End If

			If LoadAnalysis Then
				tableAnalysis.Rows.Add(rowchoice)
			Else
				table.Rows.Add(rowchoice)
			End If

		Next

		If LoadAnalysis Then
			tableAnalysis.Width = New Unit(100, UnitType.Percentage)
			cell.Controls.Add(tableAnalysis)
		Else
			table.Width = New Unit(100, UnitType.Percentage)
			cell.Controls.Add(table)
		End If

	End Sub

	Protected Sub BuildMatrixMultipleAnswersPerRow(ByVal FormQuestionID As String, ByVal FormResponseGuid As Guid, ByVal ValidationGroup As String, ByVal LoadAnswers As Boolean, ByVal cell As HtmlTableCell, ByVal QuestionDetail As FormQuestionDetail, ByVal LoadAnalysis As Boolean)

		Dim list As New FormList()
		Dim DTColumns As New DataTable()
		Dim DTRows As New DataTable()
		Dim DRCols As DataRow
		Dim DRRows As DataRow

		DTColumns = list.GetQuestionColumns(ConvertToGuid(FormQuestionID))
		DTRows = list.GetQuestionRows(ConvertToGuid(FormQuestionID))

		Dim table As New Table
		Dim tableAnalysis As New Table
		Dim rowheader As New TableRow
		Dim cellheader As New TableCell

		table.ID = String.Format("ux_{0}_MatrixRadioButtonTable", FormQuestionID)
		rowheader.ID = String.Format("ux_{0}_MatrixRowHeader", FormQuestionID)
		cellheader.ID = String.Format("ux_{0}_MatrixCellHeader", FormQuestionID)

		tableAnalysis.ID = GenerateID()
		tableAnalysis.SkinID = "FORM_SURVEY_RESULTS_TABLE"

		If LoadAnalysis Then
			cellheader.SkinID = "FORM_SURVEY_RESULTS_HEADER_TABLECELL"
		End If

		cellheader.Controls.Add(BuildLabel(GenerateID(), String.Empty))

		rowheader.Cells.Add(cellheader)

		For Each DRCols In DTColumns.Rows
			Dim cellAnalysis As New TableCell
			cellAnalysis.ID = GenerateID()

			If LoadAnalysis Then
				cellAnalysis.SkinID = "FORM_SURVEY_RESULTS_HEADER_TABLECELL"
			End If

			cellAnalysis.Controls.Add(BuildLabel(GenerateID(), DRCols("ColumnChoice").ToString()))

			rowheader.Cells.Add(cellAnalysis)

		Next

		If LoadAnalysis Then
			Dim cellResponses As New TableCell
			cellResponses.ID = GenerateID()
			cellResponses.SkinID = "FORM_SURVEY_RESULTS_HEADER_TABLECELL"
			cellResponses.Controls.Add(BuildLabel(GenerateID(), "Responses"))
			rowheader.Cells.Add(cellResponses)
		End If

		If LoadAnalysis Then
			tableAnalysis.Rows.Add(rowheader)
		Else
			table.Rows.Add(rowheader)
		End If

		For Each DRRows In DTRows.Rows
			Dim rowchoice As New TableRow
			Dim cellChoice As New TableCell
			cellChoice.ID = GenerateID()

			Dim ResponseCount As Integer = 0

			If LoadAnalysis Then
				cellChoice.SkinID = "FORM_SURVEY_RESULTS_ITEM_TABLECELL"
			End If

			rowchoice.ID = String.Format("ux_{0}_RowChoice", DRRows("FormRowID"))
			cellChoice.Controls.Add(BuildLabel(GenerateID(), DRRows("RowChoice").ToString()))
			rowchoice.Cells.Add(cellChoice)

			For Each DRCols In DTColumns.Rows
				If LoadAnalysis Then

					Dim item As FormList = New FormList()

					Dim DT As New DataTable

					DT = item.GetMatrixMultipleAnswerResults(ConvertToGuid(FormQuestionID), ConvertToGuid(DRRows("FormRowID").ToString()), ConvertToGuid(DRCols("FormColumnID").ToString()))

					Dim cellChoiceAnalysis As New TableCell
					cellChoiceAnalysis.ID = GenerateID()
					cellChoiceAnalysis.SkinID = "FORM_SURVEY_RESULTS_ITEM_TABLECELL"

					If DT.Rows.Count > 0 Then
						Dim row As DataRow

						For Each row In DT.Rows

							cellChoiceAnalysis.Controls.Add(BuildLabel(String.Format("{0}", Guid.NewGuid()), FormatResultPercentage(GetResultPercentage(row("answercount"), row("divisor")))))
							rowchoice.Cells.Add(cellChoiceAnalysis)

							ResponseCount += Convert.ToInt64(row("answercount").ToString())
						Next

					Else
						cellChoiceAnalysis.Controls.Add(BuildLabel(String.Format("{0}", Guid.NewGuid()), FormatResultPercentage(0)))

						rowchoice.Cells.Add(cellChoiceAnalysis)
					End If

				Else

					If LoadAnswers Then

						Dim cb As CheckBox

						cb = BuildCheckBox(String.Format("{0}_{1}_{2}", FormQuestionID, DRRows("FormRowID"), DRCols("FormColumnID").ToString()), String.Empty)

						Dim fl As New FormList
						Dim DT As New DataTable

						DT = fl.GetAnswersForRowsColumns(ConvertToGuid(FormQuestionID), FormResponseGuid, ConvertToGuid(DRRows("FormRowID").ToString), ConvertToGuid(DRCols("FormColumnID").ToString()))

						If DT.Rows.Count > 0 Then
							cb.Checked = True
						End If

						cb.Enabled = False

						rowchoice.Cells.Add(BuildCell(String.Format("{0}_{1}", DRRows("FormRowID"), DRCols("FormColumnID").ToString()), cb))
					Else
						rowchoice.Cells.Add(BuildCell(String.Format("{0}_{1}", DRRows("FormRowID"), DRCols("FormColumnID").ToString()), BuildCheckBox(String.Format("{0}_{1}_{2}", FormQuestionID, DRRows("FormRowID"), DRCols("FormColumnID").ToString()), String.Empty)))
					End If

				End If
			Next

			If LoadAnalysis Then
				Dim cellChoiceResponses As New TableCell
				cellChoiceResponses.ID = GenerateID()
				cellChoiceResponses.SkinID = "FORM_SURVEY_RESULTS_ITEM_TABLECELL"
				cellChoiceResponses.Controls.Add(BuildLabel(String.Format("{0}", Guid.NewGuid()), ResponseCount))

				rowchoice.Cells.Add(cellChoiceResponses)
			End If

			If LoadAnalysis Then
				tableAnalysis.Rows.Add(rowchoice)
			Else
				table.Rows.Add(rowchoice)
			End If

		Next

		If LoadAnalysis Then
			tableAnalysis.Width = New Unit(100, UnitType.Percentage)
			cell.Controls.Add(tableAnalysis)
		Else
			table.Width = New Unit(100, UnitType.Percentage)
			cell.Controls.Add(table)
		End If

	End Sub

#End Region

#End Region

#Region " Build Validators "

    Protected Function BuildValidationSummary(ByVal ID As String, ByVal ValidationGroup As String, ByVal DisplayMode As ValidationSummaryDisplayMode) As ValidationSummary

        Dim vs As New ValidationSummary

        vs.ID = ID
        vs.ValidationGroup = ValidationGroup
        vs.DisplayMode = DisplayMode

        Return vs

    End Function

    Protected Function BuildRequiredFieldValidator(ByVal ControlToValidate As String, ByVal ErrorMessage As String, ByVal ValidationGroup As String, ByVal DisplayMode As ValidatorDisplay) As RequiredFieldValidator
        Dim rfv As New RequiredFieldValidator

		rfv.ID = String.Format("{0}_RFV", ControlToValidate.Replace("-", ""))
        rfv.ControlToValidate = ControlToValidate
        rfv.ValidationGroup = ValidationGroup
        rfv.SetFocusOnError = True
        rfv.ErrorMessage = ErrorMessage
        rfv.Display = DisplayMode

        rfv.Controls.Add(BuildErrorImage(String.Format("{0}_RFV", ControlToValidate)))

        Return rfv

    End Function

    Protected Function BuildCompareFieldValidator(ByVal ControlToValidate As String, ByVal ErrorMessage As String, ByVal ValidationGroup As String, ByVal DisplayMode As ValidatorDisplay, ByVal DataType As ValidationDataType) As CompareValidator
        Dim cv As New CompareValidator

		cv.ID = String.Format("{0}CV", ControlToValidate.Replace("-", ""))
        cv.ControlToValidate = ControlToValidate
        cv.ValidationGroup = ValidationGroup
        cv.SetFocusOnError = True
        cv.ErrorMessage = ErrorMessage
        cv.Display = DisplayMode
        cv.Operator = ValidationCompareOperator.DataTypeCheck
        cv.Type = DataType

        cv.Controls.Add(BuildErrorImage(String.Format("{0}_CFV", ControlToValidate)))

        Return cv
    End Function

    Protected Function BuildRegularExpressionValidator(ByVal ControlToValidate As String, ByVal ErrorMessage As String, ByVal ValidationGroup As String, ByVal DisplayMode As ValidatorDisplay, ByVal Expression As String) As RegularExpressionValidator
        Dim rev As New RegularExpressionValidator

		rev.ID = String.Format("{0}_REV", ControlToValidate.Replace("-", ""))
        rev.ControlToValidate = ControlToValidate
        rev.ValidationGroup = ValidationGroup
        rev.SetFocusOnError = True
        rev.ErrorMessage = ErrorMessage
        rev.Display = DisplayMode
        rev.ValidationExpression = Expression

        rev.Controls.Add(BuildErrorImage(String.Format("{0}_REV", ControlToValidate)))

        Return rev
    End Function

    Protected Function BuildRangeValidator(ByVal ControlToValidate As String, ByVal ErrorMessage As String, ByVal ValidationGroup As String, ByVal DisplayMode As ValidatorDisplay, ByVal MinimumValue As String, ByVal MaximumValue As String) As RangeValidator
        Dim rv As New RangeValidator

		rv.ID = String.Format("{0}_REV", ControlToValidate.Replace("-", ""))
        rv.ControlToValidate = ControlToValidate
        rv.ValidationGroup = ValidationGroup
        rv.SetFocusOnError = True
        rv.ErrorMessage = ErrorMessage
        rv.Display = DisplayMode
        rv.MinimumValue = MinimumValue
        rv.MaximumValue = MaximumValue

        rv.Controls.Add(BuildErrorImage(String.Format("{0}_RV", ControlToValidate)))

        Return rv
	End Function

	Protected Function BuildCheckBoxListRequiredFieldValidator(ByVal ControlToValidate As String, ByVal ErrorMessage As String, ByVal ValidationGroup As String, ByVal DisplayMode As ValidatorDisplay) As CheckBoxListRequiredFieldValidator
		Dim cbfv As New CheckBoxListRequiredFieldValidator

		cbfv.ID = String.Format("{0}_CBFV", ControlToValidate.Replace("-", ""))
		cbfv.ControlToValidate = ControlToValidate
		cbfv.ValidationGroup = ValidationGroup
		cbfv.SetFocusOnError = True
		cbfv.ErrorMessage = ErrorMessage
		cbfv.Display = DisplayMode

		cbfv.Controls.Add(BuildErrorImage(String.Format("{0}_CBFV", ControlToValidate)))

		Return cbfv

	End Function

	Protected Function BuildRadioButtonListRequiredFieldValidator(ByVal ControlToValidate As String, ByVal ErrorMessage As String, ByVal ValidationGroup As String, ByVal DisplayMode As ValidatorDisplay) As RadioButtonListRequiredFieldValidator
		Dim rbfv As New RadioButtonListRequiredFieldValidator

		rbfv.ID = String.Format("{0}_RBFV", ControlToValidate.Replace("-", ""))
		rbfv.ControlToValidate = ControlToValidate
		rbfv.ValidationGroup = ValidationGroup
		rbfv.SetFocusOnError = True
		rbfv.ErrorMessage = ErrorMessage
		rbfv.Display = DisplayMode

		rbfv.Controls.Add(BuildErrorImage(String.Format("{0}_RBFV", ControlToValidate)))

		Return rbfv

	End Function

	Protected Function BuildCheckBoxListDependantControlValidator(ByVal ControlToValidate As String, ByVal ErrorMessage As String, ByVal ValidationGroup As String, ByVal DisplayMode As ValidatorDisplay, ByVal ValueToCheck As String, ByVal TargetControlID As String, ByVal TargetControlType As BA.Validators.CheckBoxListDependantControlValidator.TargetControlType) As CheckBoxListDependantControlValidator
		Dim cbdcfv As New CheckBoxListDependantControlValidator

		cbdcfv.ID = String.Format("{0}_CBDCFV", ControlToValidate.Replace("-", ""))
		cbdcfv.ControlToValidate = ControlToValidate
		cbdcfv.ValidationGroup = ValidationGroup
		cbdcfv.SetFocusOnError = True
		cbdcfv.ErrorMessage = ErrorMessage
		cbdcfv.Display = DisplayMode
		cbdcfv.ValueToCheck = ValueToCheck
		cbdcfv.TargetControlID = TargetControlID
		cbdcfv.TargetControlTypeSelection = TargetControlType

		cbdcfv.Controls.Add(BuildErrorImage(String.Format("{0}_CBDCFV", ControlToValidate)))

		Return cbdcfv

	End Function

	Protected Function BuildRadioButtonDependantControlValidator(ByVal ControlToValidate As String, ByVal ErrorMessage As String, ByVal ValidationGroup As String, ByVal DisplayMode As ValidatorDisplay, ByVal ValueToCheck As String, ByVal TargetControlID As String, ByVal TargetControlType As BA.Validators.CheckBoxListDependantControlValidator.TargetControlType) As RadioButtonDependantControlValidator
		Dim rbdcfv As New RadioButtonDependantControlValidator

		rbdcfv.ID = String.Format("{0}_RBDCFV", ControlToValidate.Replace("-", ""))
		rbdcfv.ControlToValidate = ControlToValidate
		rbdcfv.ValidationGroup = ValidationGroup
		rbdcfv.SetFocusOnError = True
		rbdcfv.ErrorMessage = ErrorMessage
		rbdcfv.Display = DisplayMode
		rbdcfv.ValueToCheck = ValueToCheck
		rbdcfv.TargetControlID = TargetControlID
		rbdcfv.TargetControlTypeSelection = TargetControlType

		rbdcfv.Controls.Add(BuildErrorImage(String.Format("{0}_RBDCFV", ControlToValidate)))

		Return rbdcfv

	End Function

#End Region

#Region " Build General Controls "

    Protected Function BuildCell(ByVal ID As String, ByVal Ctl As Control) As TableCell
        Dim cell As New TableCell

        cell.ID = String.Format("ux_{0}_Cell", ID)
        cell.Controls.Add(Ctl)

        Return cell
    End Function

    Protected Function BuildRow(ByVal ID As String, ByVal Cell As TableCell) As TableRow
        Dim row As New TableRow

        row.ID = String.Format("ux_{0}_Row", ID)
        row.Cells.Add(Cell)

        Return row
    End Function

    Protected Function BuildRadioButton(ByVal ID As String, ByVal Text As String, ByVal GroupName As String) As RadioButton
        Dim rb As New RadioButton

        rb.ID = String.Format("ux_{0}_RadioButton", ID)
        rb.Text = Text
        rb.GroupName = GroupName

        Return rb

    End Function

    Protected Function BuildCheckBox(ByVal ID As String, ByVal Text As String) As CheckBox
        Dim cb As New CheckBox

        cb.ID = String.Format("ux_{0}_CheckBox", ID)
        cb.Text = Text

        Return cb

    End Function

    Protected Function BuildLabel(ByVal ID As String, ByVal Text As String) As Label
        Dim lbl As New Label

        lbl.ID = String.Format("ux_{0}_Label", ID)
        lbl.Text = Text

        Return lbl

    End Function

    Protected Function BuildErrorImage(ByVal ID As String) As System.Web.UI.WebControls.Image
        Dim image As New System.Web.UI.WebControls.Image

        image.ID = String.Format("{0}_ErrorImage", ID)
        image.SkinID = "errorimage"

        Return image
    End Function

    Protected Function BuildSpacerImage(ByVal ID As String) As System.Web.UI.WebControls.Image
        Dim image As New System.Web.UI.WebControls.Image

        image.ID = String.Format("{0}_SpacerImage", ID)
        image.SkinID = "spacer"

        Return image
    End Function

    Protected Function BuildCalendarImage(ByVal ID As String) As System.Web.UI.WebControls.Image
        Dim image As New System.Web.UI.WebControls.Image

        image.ID = String.Format("{0}_DateImage", ID)
        image.SkinID = "calendar"

        Return image
    End Function

    Protected Function BuildCalendarExtender(ByVal ID As String, ByVal TargetControlID As String, ByVal ImageControlID As String) As AjaxControlToolkit.CalendarExtender

        Dim ce As New AjaxControlToolkit.CalendarExtender

        ce.ID = String.Format("{0}_CalendarExtender", ID)
        ce.TargetControlID = TargetControlID
        ce.PopupButtonID = ImageControlID
        ce.CssClass = "Calendar"
        ce.FirstDayOfWeek = WebControls.FirstDayOfWeek.Default
        ce.Animated = True

        Return ce

    End Function

#End Region

#Region " Helpers "

    Protected Function FormatResultPercentage(ByVal Result As Double) As String

        Return String.Format("{0}%", Result)

    End Function

    Protected Function GenerateID() As String
        Return String.Format("ux_{0}_DisplayItem", Guid.NewGuid.ToString())
    End Function

    Protected Function GetResultPercentage(ByVal AnswerCount As Integer, ByVal Divisor As Integer) As Double

        If Divisor = 0 Then
            Return 0.0
        Else
            Return System.Math.Round(((AnswerCount / Divisor) * 100), 1)
        End If

    End Function


#End Region

#End Region

End Class

